package com.example.yuda.myserviceapplication;

import java.io.IOException;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;

public class MyService extends Service{
    //播放媒体资源的需要用到 mediaPlayer对象
    private MediaPlayer mPlayer;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("", "MyService onCreate");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("", "MyService onStartCommand");
        int action = intent.getIntExtra("action", -1);
        if(action == 1){
            play();
        } else if(action == 2){
            pause();
        } else if(action == 3){
            stop();
        }

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("", "MyService onDestroy");
        //服务结束的时候，释放媒体资源
        if(mPlayer != null){
            mPlayer.stop();
            mPlayer.release();
            mPlayer = null;
        }
    }

    /**
     * 播放音乐
     */
    private void play(){
        if(mPlayer == null){
            mPlayer = MediaPlayer.create(this, R.raw.abc);
        }
        if(!mPlayer.isPlaying()){//判断音乐是否播放
            mPlayer.start();
        }
    }


    /**
     * 停止
     */
    private void stop(){
        if(mPlayer.isPlaying()){
            mPlayer.stop();
            //如果停止了之后还需要再次播放，需要调用下面一行代码
            try {
                mPlayer.prepare();
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    /**
     * 暂停
     */
    private void pause(){
        if(mPlayer.isPlaying()){
            mPlayer.pause();
        }
    }
}
